<style lang="less">
  @import './data-structure.less';
</style>

<template>
  <div class="data-structure">
    <div class="title-option-box">
      <h1 class="title">数据结构</h1>
      <p class="option">
        <Button type="primary" @click="prevBtn">
          <Icon type="ios-arrow-back" size="15"></Icon>
        </Button>
        <Button @click="nextBtn" type="primary">
          <Icon type="ios-arrow-forward" size="15"></Icon>
        </Button>
      </p>
    </div>
    <div class="data-structure-content clearfix">
      <!-- 输入数据 -->
      <div class="left-area scrollbar-small">
        <div class="option-box clearfix">
          <h2 class="subtitle">输入数据</h2>
          <span class="btn-box">
            <Button type="primary" size="small" @click="saveNewData('inputData')">保存</Button>
            <Button type="primary" size="small" @click="addNewData('inputData')">新增</Button>
            <Button type="primary" size="small" @click="deleteNewData('inputData')">删除</Button>
            <Button type="primary" size="small" @click="downLoadData('inputData')">导出</Button>
          </span>
        </div>
        <Table
          @on-selection-change="selectInputData"
          :columns="inputTableColumns"
          :data="inputTableData"
          :no-data-text="inputNoData"
          ></Table>
      </div>
      <!-- 输出数据 -->
      <div class="right-area scrollbar-small">
        <div class="option-box clearfix">
          <h2 class="subtitle">输出数据</h2>
          <span class="btn-box">
            <Button type="primary" size="small" @click="saveNewData('outputData')">保存</Button>
            <Button type="primary" size="small" @click="addNewData('outputData')">新增</Button>
            <Button type="primary" size="small" @click="deleteNewData('outputData')">删除</Button>
            <Button type="primary" size="small" @click="downLoadData('outputData')">导出</Button>
          </span>
        </div>
        <Table
          @on-selection-change="selectOutputData"
          :columns="outputTableColumns"
          :data="outputTableData"
          :no-data-text="outputNoData"
          ></Table>
      </div>
    </div>
    <!-- 新增数据modal框 -->
    <Modal
      width="600"
      class="add-newdata-modal"
      v-model="newDataModalShow"
      title="新增数据"
      :closable="false"
      :mask-closable="false"
      :transfer="false"
      >
        <Tabs class="add-newdata-tab" v-model="currentTabs">
          <TabPane class="general-data-tab" label="从通用数据库选择" name="generalData">
            <p class="filter-board">
              <b>数据分类：</b>
              <Cascader
                class="DS_operation_large"
                :data="dataTypeDict"
                v-model="dataType"
                change-on-select></Cascader>
              <Button type="primary" @click="() => getGenTableData()">筛选</Button>
            </p>
            <Table
              @on-selection-change="selectgeneraData"
              :columns="generalDataColumns"
              :data="generalDataTableData"
              :no-data-text="generalDataNoData"
              ></Table>
              <Page
                style="float: right; padding-top: 8px;"
                show-elevator
                show-total
                show-sizer
                size="small"
                :current="page"
                :total="pageTotal"
                :page-size="pageSize"
                @on-change="(number) => getGenTableData(number)"></Page>
          </TabPane>
          <TabPane class="base-data-tab" label="新建基本数据结构" name="baseData">
          <base-form
            formRef="baseData"
            ref="baseData"
            :typeDict="dataTypeDict"
            :classDict="dataClassDict"
            :tableData="mergeTableData"
            >
            <!-- <div class="slot-footer">
              <Button @click="cancelFirstModal">取消</Button>
              <Button type="primary" @click="certainBaseDataModal">确定</Button>
            </div> -->
          </base-form>
          </TabPane>
          <TabPane class="derivative-data-tab" label="新建衍生数据结构" name="derivativeData">
            <base-form
              formRef="derivativeData"
              ref="derivativeData"
              :typeDict="dataTypeDict"
              :classDict="dataClassDict"
              :tableData="mergeTableData"
              >
              <!-- <div class="slot-footer">
                <Button @click="cancelFirstModal">取消</Button>
                <Button type="primary" @click="toEditRules">确定</Button>
              </div> -->
            </base-form>
          </TabPane>
          <TabPane class="import-file-tab" label="导入文件" name="importFile">
            <Upload
              multiple
              type="drag"
              action="//jsonplaceholder.typicode.com/posts/">
              <div style="padding: 100px 0">
                <Icon type="ios-cloud-upload" size="52" style="color: #3399ff"></Icon>
                <p>将文件拖拽至此处或点击上传</p>
              </div>
            </Upload>
            <p style="text-align: center">仅支持上传.excel文件，且文件不超过10MB，<a>样例下载</a></p>
          </TabPane>
        </Tabs>
        <div slot="footer">
          <Button @click="cancelNewDataModal">取消</Button>
          <Button type="primary" v-if="currentTabs === 'derivativeData'" @click="toCreateRules">编辑规则</Button>
          <Button type="primary" v-else @click="certainNewDataModal">确定</Button>
        </div>
      </Modal>
      <!-- 编辑 -->
      <Modal
        width="600"
        class="edit-newdata-modal"
        v-model="editDataModalShow"
        title="编辑数据"
        :closable="false"
        :mask-closable="false"
        :transfer="false"
        >
          <base-form
            formRef="editBaseForm"
            ref="editBaseForm"
            :codeDisabled="true"
            :typeDict="dataTypeDict"
            :classDict="dataClassDict"
            :tableData="mergeTableData"
            :formData="editBaseForm"
            >
          </base-form>
          <!-- todo 根据点击的列表获取是否有编辑规则的权限 -->
          <div slot="footer">
            <Button @click="cancelEditDataModal">取消</Button>
            <Button type="primary" v-if="editBaseForm.dataMode === 'DERIVATIVE'" @click="toEditRules">编辑规则</Button>
            <Button type="primary" v-else @click="() => certainEditDataModal()">确定</Button>
          </div>
        </Modal>
      <!-- 编辑衍生规则modal页 -->
      <Modal
        width="1000"
        class="add-derivative-modal"
        v-model="derivativeRuleShow"
        title="编辑衍生数据"
        :closable="false"
        :mask-closable="false"
        :transfer="false"
        >
        <div class="derivative-content clearfix">
          <ul class="left-content">
            <li class="left-content-data">
              <p class="filter-board">
                <b>数据分类</b>
                <Cascader
                  style="width: 375px;"
                  :data="dataTypeDict"
                  v-model="DerivativeDataType"
                  change-on-select
                  @on-change="changeDerivativeDataType"></Cascader>
              </p>
              <div class="class-box data-class-box scrollbar-small">
                <p v-if="derInputData.length < 1">暂无数据</p>
                <Button
                  class="data-item DS_ellipsis"
                  v-for="item in derInputData"
                  :key="item.dataCode"
                  :title="item.dataName"
                  @click="handleClickDerItem(item)">{{ item.dataName }}</Button>
              </div>
            </li>
            <li class="left-content-methods">
              <p class="filter-board">
                <b>方法分类</b>
                <Select v-model="currentMethodCode" @on-change="changeMethodList">
                  <Option v-for="item in commonMethodList" :key="item.resId" :value="item.resId">{{ item.resName }}</Option>
                </Select>
              </p>
              <div class="class-box method-class-box scrollbar-small">
                <p v-if="methodContent.length < 1">暂无数据</p>
                <Button
                  class="data-item DS_ellipsis"
                  v-for="item in methodContent"
                  :title="item.methodName"
                  :key="item.methodCode"
                  @click="handleClickMethod(item)"
                >{{ item.methodName }}</Button>
                <p>
                  <Button
                    class="data-item DS_ellipsis"
                    :title="item.methodName"
                    :key="item.methodCode"
                    v-for="item in symbolContent"
                    @click="handleClickMethod(item)"
                  >{{ item.methodName }}</Button>
                </p>
              </div>
            </li>
            <li class="left-content-value">
              <p class="filter-board">
                <b>运算值</b>
                <Input v-model="operationalValue" @on-enter="handleEnter" placeholder="输入按enter添加"></Input>
              </p>
            </li>
          </ul>
          <div class="right-content">
            <!-- 视图模式 -->
            <div class="view-model">
              <!-- <el-tag :key="i" v-for="(val,i) in ruleTagsShow" closable :disable-transitions="false" @close="tagRuleClose(val,i)" @click.native="ruleTagsClick(i)" size="mini" :class="{activeTag : (activeTagData == i && activeTagData != null)}" :style="{'color': val == ')' || val == '(' ? 'red' : '#409EFF'}"> -->
              <Tag
                v-for="(item, index) in viewList"
                :key="`item${index}`"
                :name="item"
                closable
                @on-close="() => handleCloseTag(item, index)"
                :class="['view-tag', currentTagIndex == index ? 'active-tag' : '']"
                @click.native="handleClickTag(index, item)"
              >{{ item }}</Tag>
            </div>
            <!-- 源码模式 -->
            <!-- <div class="code-model">
              <editor v-model="ruleScript" @init="editorInit" lang="drools" theme="chrome" ref="editor" enableBasicAutocompletion="true" enableSnippets="true" enableLiveAutocompletion="true" class="ruleShowSpace"></editor>
            </div> -->
          </div>
        </div>

        <div class="derivative-footer clearfix" slot="footer">
          <!-- <p class="left-btn">
            <RadioGroup v-model="currentDerivativeModel" type="button" size="large">
              <Radio label="viewModel" :disabled="currentDerivativeModel === 'codeModel' && ruleScript.length > 0">视图模式</Radio>
              <Radio label="codeModel">源码模式</Radio>
            </RadioGroup>
          </p> -->
          <p class="right-btn">
            <Button @click="clearRule">
              清空
            </Button>
            <Button @click="cancelDerivativeEdit">取消</Button>
            <Button type="primary" @click="certainDerivativeEdit">确定</Button>
          </p>
        </div>
      </Modal>
  </div>
</template>

<script>
import { addProp, setDsResource, showMessageTip, getAllParentCodes } from '@/libs/util'
import baseForm from './components/base-form'
import { updateResourceContentByIdApi, queryResourceContentByIdApi, verification } from '@/api/project-resource'
import { queryTempApi } from '@/api/data-management'
import { queryDictByKeyApi } from '@/api/business-type'
import { queryMethodJarApi, queryMethodApi } from '@/api/method-management'
import { derivativeComputation, derivativeSymbol } from '../commonMethodContent'
import { mapMutations } from 'vuex'

export default {
  name: 'data_structure',
  props: ['createId'],
  data () {
    return {
      // 资源id列表
      resIdList: null,
      // 输入数据版本id
      inputResVerId: null,
      // 输出数据版本id
      outputResVerId: null,
      // 输入数据
      inputContent: null,
      inputTableColumns: [],
      inputTableData: [],
      inputNoData: '加载中...',
      // 输入数据选中项
      inputSelectedData: [],
      // 输出数据
      outputContent: null,
      outputTableColumns: [],
      outputTableData: [],
      outputNoData: '加载中...',
      outputSelectedData: [],

      // 新增or编辑数据modal框相关
      newDataModalShow: false,
      // 当前tab
      currentTabs: 'generalData',
      // 记录当前为输入or输出
      currentAddBtn: '',
      // 通用数据库选择表格相关
      dataTypeDict: [],
      dataType: [],
      generalDataColumns: [],
      generalDataTableData: [],
      selectGenTableData: [], // 选中数据
      generalDataNoData: '加载中...',
      page: 1,
      pageSize: 40,
      pageTotal: 0,
      editDataModalShow: false,

      // 编辑基本数据赋值表单
      editBaseForm: {},

      /* 编辑衍生规则modal框相关 */
      // 新建衍生or编辑衍生标识
      isNewDerivative: false,
      derivativeRuleShow: false,
      // 数据分类绑定值
      DerivativeDataType: [],
      // 输入数据列表
      derInputData: [],
      viewList: [],
      sourceList: [],
      // 方法分类下拉
      commonMethodList: [],
      currentMethodCode: 'COMMONMETHOD',
      methodContent: [],
      // 运算值
      operationalValue: '',
      // 计算符
      commonMethodContent: derivativeComputation,
      // 符号
      symbolContent: derivativeSymbol,
      // 选中的tag索引
      currentTagIndex: null

      // ruleScript: '', // 源码模式 输入框内容
      // editorCtrl: ''

    }
  },
  components: {
    baseForm,
    editor: require('vue2-ace-editor')
  },
  computed: {
    projectId () {
      return this.$route.params.projectId === '_create' ? this.createId : this.$route.params.projectId
    },
    mergeTableData () {
      return this.inputTableData.concat(this.outputTableData)
    },
    // 数据模式字典（通用、自建、衍生）
    dataModeDict () {
      const filterList = this.$store.state.app.dictList.filter(item => item.id === 205)[0]
      const result = filterList && filterList.children ? filterList.children : []
      return result
    },
    // 数据类型字典
    dataClassDict () {
      const filterList = this.$store.state.app.dictList.filter(item => item.id === 198)[0]
      const result = filterList && filterList.children ? filterList.children : []
      return result
    }
  },
  methods: {
    ...mapMutations([
      'setDataStructure'
    ]),
    init (resIdList) {
      this.resIdList = resIdList
      this.getTableData()
    },
    // editorInit (initCtrl) {
    //   require('brace/ext/language_tools') // language extension prerequsite...
    //   require('brace/mode/drools') // language
    //   require('brace/theme/chrome')
    //   require('brace/snippets/drools') // snippet
    //   initCtrl.setOptions({
    //     enableBasicAutocompletion: true,
    //     enableLiveAutocompletion: true
    //   })
    //   initCtrl.setFontSize(14)
    //   this.editorCtrl = initCtrl
    //   // initCtrl.setReadOnly(true)
    // },
    setTableColumns () {
      const inputTableColumns = [{
        type: 'selection',
        align: 'center',
        width: 60
      }, {
        key: 'dataName',
        title: '数据名称'
      }, {
        key: 'dataCode',
        title: '数据编码'
      }, {
        key: 'dataLength',
        title: '数据长度'
      }, {
        key: 'dataClass',
        title: '数据类型'
      }, {
        key: 'dataTypeName',
        title: '数据分类'
      }, {
        key: 'dataMode',
        title: '数据来源',
        render: (h, { row }) => {
          const result = this.dataModeDict.filter(item => item.dictKey === row.dataMode)[0]
          const text = result && result.label ? result.label : ''
          return (
            <span>{text}</span>
          )
        }
      }, {
        title: '操作',
        render: (h, { row }) => {
          const self = this
          return (
            <a onClick={ () => self.editDetail(row) }>{ row.dataMode === 'CUSTOM' ? '编辑' : row.dataMode === 'DERIVATIVE' ? '编辑衍生' : '' }</a>
          )
        }
      }]
      this.inputTableColumns = inputTableColumns
      this.outputTableColumns = inputTableColumns
      const generalDataColumns = JSON.parse(JSON.stringify(inputTableColumns))
      generalDataColumns.splice(6, 2)
      this.generalDataColumns = generalDataColumns
    },
    resetTableData () {

    },
    getTableData () {
      // this.inputTableData = inputData
      // this.outputTableData = ouputData
      this.getInputTableData()
      this.getOutputTableData()
    },
    // 获取输入数据表格
    getInputTableData () {
      const inputDataResIdTmp = this.resIdList.filter(item => item.dataType === 'input')[0]
      const inputDataResId = inputDataResIdTmp && inputDataResIdTmp.resId ? inputDataResIdTmp.resId : ''
      this.inputDataResId = inputDataResId

      const inputParams = {
        projectId: this.projectId,
        resId: inputDataResId
      }
      queryResourceContentByIdApi(inputParams).then((res) => {
        if (res.data.code === 2000) {
          this.inputTableData = res.data.data && res.data.data.dataDefines ? res.data.data.dataDefines : []
          this.inputResVerId = res.data.data && res.data.data.resVerId ? res.data.data.resVerId : ''
          this.inputNoData = this.inputTableData && this.inputTableData.length ? '' : '未查询到数据'
          this.derInputData = JSON.parse(JSON.stringify(this.inputTableData))
          // 存储到store 用于规则、决策流
          const saveInputInfo = {
            pathname: window.location.pathname,
            targetKey: 'inputDataList',
            resourceList: JSON.parse(JSON.stringify(this.inputTableData))
          }
          this.setDataStructure(saveInputInfo)
        }
      })
    },
    // 获取输出数据表格
    getOutputTableData () {
      const outputDataResIdTmp = this.resIdList.filter(item => item.dataType === 'output')[0]
      const outputDataResId = outputDataResIdTmp && outputDataResIdTmp.resId ? outputDataResIdTmp.resId : ''
      this.outputDataResId = outputDataResId

      // 输出数据content接口
      const outputParams = {
        projectId: this.projectId,
        resId: outputDataResId
      }
      queryResourceContentByIdApi(outputParams).then((res) => {
        if (res.data.code === 2000) {
          this.outputTableData = res.data.data && res.data.data.dataDefines ? res.data.data.dataDefines : []
          const outputList = this.outputTableData.map(item => {
            return {
              name: item.dataName,
              value: item.dataCode
            }
          })
          this.outputResVerId = res.data.data && res.data.data.resVerId ? res.data.data.resVerId : ''
          this.outputNoData = this.outputTableData && this.outputTableData.length ? '' : '未查询到数据'
          // 存储到session用于决策流
          setDsResource(window.location.pathname, 'outputList', outputList)
          // 存储到store 用于规则、决策流
          const saveInputInfo = {
            pathname: window.location.pathname,
            targetKey: 'outputDataList',
            resourceList: JSON.parse(JSON.stringify(this.outputTableData))
          }
          this.setDataStructure(saveInputInfo)
        }
      })
    },
    prevBtn () {
      const params = {
        activeName: 'dataStructure',
        option: 'prev'
      }
      this.$emit('on-move-forward', params)
    },
    nextBtn () {
      const params = {
        activeName: 'dataStructure',
        option: 'next'
      }
      this.$emit('on-move-forward', params)
    },
    // 保存按钮
    saveNewData (target) {
      const resId = target === 'inputData' ? this.inputDataResId : this.outputDataResId
      const params = {
        projectId: this.projectId,
        resId
      }
      const dataDefines = target === 'inputData' ? this.inputTableData : this.outputTableData

      const data = {
        dataDefines,
        resId,
        resVerId: target === 'inputData' ? this.inputResVerId : this.outputResVerId,
        contentType: 'data'
      }
      updateResourceContentByIdApi(params, data).then((res) => {
        const code = res.data.code
        const successText = '保存成功'
        const errorText = res.data.msg || '保存失败，请重试'
        showMessageTip(this, code, successText, errorText)
        if (code === 2000) {
          target === 'inputData' ? this.getInputTableData() : this.getOutputTableData()
        }
      })
    },
    // 新增按钮
    addNewData (target) {
      // todo 重置表单验证
      this.currentAddBtn = target
      this.newDataModalShow = true
      this.selectGenTableData = []
      // 获取通用数据表格
      this.getGenTableData()
    },
    // 删除按钮
    deleteNewData (target) {
      if (target === 'inputData') {
        const selected = this.inputSelectedData.map(item => item.dataCode)
        this.inputTableData = this.inputTableData.filter(item => selected.indexOf(item.dataCode) < 0)
      } else {
        const selected = this.outputSelectedData.map(item => item.dataCode)
        this.outputTableData = this.outputTableData.filter(item => selected.indexOf(item.dataCode) < 0)
      }
    },
    // 导出按钮
    downLoadData (target) {
      console.log('---target', target)
    },
    // 输入数据 表格 选中事件
    selectInputData (select) {
      this.inputSelectedData = select
    },
    // 输出数据 表格 选中事件
    selectOutputData (select) {
      this.outputSelectedData = select
    },
    // 新建衍生规则基本信息确定按钮事件
    toCreateRules () {
      const currentTabs = this.currentTabs
      this.$refs[currentTabs].$refs[currentTabs].validate((valid) => {
        // todo判断编码是否已存在接口，若不存在则push此formData到输入or输出表格
        if (valid) {
          const basedataForm = JSON.parse(JSON.stringify(this.$refs[currentTabs].basedataForm))
          basedataForm.dataMode = 'DERIVATIVE'
          // 处理数据分类传最后一个id
          basedataForm.dataTypeId = basedataForm.dataTypeIdList[basedataForm.dataTypeIdList.length - 1] || ''
          // 衍生规则传空
          basedataForm.dataFormat = []
          basedataForm.dataFormula = []
          const tableData = this.currentAddBtn === 'inputData' ? this.inputTableData : this.outputTableData
          tableData.push(basedataForm)

          this.derivativeForm = basedataForm
          // 新建衍生or编辑衍生标识
          this.isNewDerivative = true
          this.getMethodList()
          this.derivativeRuleShow = true
        }
      })
    },
    // 编辑列表某条详情
    editDetail (row) {
      this.editBaseForm = JSON.parse(JSON.stringify(row))
      if (this.editBaseForm.dataMode === 'DERIVATIVE') {
        this.derivativeIndex = row._index
        this.viewList = this.editBaseForm.dataFormat || []
        this.sourceList = this.editBaseForm.dataFormula || []
      }
      // 查找数据分类所有父节点
      this.editBaseForm.dataTypeIdList = getAllParentCodes(this.dataTypeDict, row.dataTypeId)
      this.editDataModalShow = true
    },
    // 编辑时 "编辑规则"按钮事件
    toEditRules () {
      this.isNewDerivative = false
      this.certainEditDataModal(true)
    },
    // 保存表单到tableData对应行
    saveEditBaseForm (formData) {
      const index = this.inputTableData.findIndex(item => item.dataCode === formData.dataCode)
      if (index > -1) {
        this.$set(this.inputTableData, index, formData)
      } else {
        const index = this.outputTableData.findIndex(item => item.dataCode === formData.dataCode)
        this.$set(this.outputTableData, index, formData)
      }
    },
    // 编辑规则modal框确定按钮
    certainEditDataModal (derivativeFlag) {
      this.$refs.editBaseForm.$refs.editBaseForm.validate((valid) => {
        if (valid) {
          const formData = JSON.parse(JSON.stringify(this.$refs.editBaseForm.basedataForm))
          this.saveEditBaseForm(formData)
          if (derivativeFlag) {
            this.getMethodList()
            this.derivativeRuleShow = true
          } else {
            this.editDataModalShow = false
          }
        }
      })
    },
    // 新增数据取消按钮
    cancelNewDataModal () {
      this.newDataModalShow = false
    },
    // 新增数据确定按钮
    certainNewDataModal () {
      const currentTabs = this.currentTabs
      switch (currentTabs) {
        // 从通用选择
        case 'generalData': // 206 COMMON
          const codeList = this.mergeTableData.map(item => item.dataCode)
          const arr = []
          this.selectGenTableData.forEach(item => {
            if (codeList.indexOf(item.dataCode) > -1) arr.push(item.dataCode)
          })
          if (arr.length > 0) {
            this.$Message.warning({
              content: `编码：${arr}已存在`,
              duration: 4
            })
          } else {
            this.currentAddBtn === 'inputData'
              ? this.inputTableData = this.inputTableData.concat(this.selectGenTableData)
              : this.outputTableData = this.outputTableData.concat(this.selectGenTableData)
            this.newDataModalShow = false
          }
          break
        // 新建基本数据结构
        case 'baseData': // 207 CUSTOM
          this.$refs[currentTabs].$refs[currentTabs].validate((valid) => {
            // todo判断编码是否已存在接口，若不存在则push此formData到输入or输出表格
            if (valid) {
              const basedataForm = JSON.parse(JSON.stringify(this.$refs[currentTabs].basedataForm))
              basedataForm.dataMode = 'CUSTOM'
              // 处理数据分类传最后一个id
              basedataForm.dataTypeId = basedataForm.dataTypeIdList[basedataForm.dataTypeIdList.length - 1] || ''
              // 衍生规则传空
              basedataForm.dataFormat = []
              const tableData = this.currentAddBtn === 'inputData' ? this.inputTableData : this.outputTableData
              tableData.push(basedataForm)
              this.newDataModalShow = false
            }
          })
          break
        // 导入文件
        case 'importFile':
          // todo 导入接口 将返回数据push到输入or输出表格
          break
        default:
          break
      }
    },
    // 编辑规则取消按钮
    cancelEditDataModal () {
      this.editDataModalShow = false
    },
    /* 从通用库选择表格相关 */
    getGenTableData (number) {
      const pageParmas = {
        page: number || this.page,
        size: this.pageSize,
        dataTypeId: this.dataType.length ? this.dataType[this.dataType.length - 1] : ''
      }
      this.generalDataTableData = []
      this.generalDataNoData = '加载中...'
      queryTempApi(pageParmas).then((res) => {
        if (res.data.code === 2000) {
          this.pageTotal = res.data.data.total
          const { data = {} } = res.data || {}
          this.generalDataTableData = data.items || []
          this.generalDataNoData = res.data.data.total ? '' : '未查询到数据'
        } else {
          this.$Message.error({
            content: res.data.msg || '加载失败，请重试',
            duration: 4
          })
        }
      })
    },
    // 新增数据-通用数据库选择 表格 选中事件
    selectgeneraData (select) {
      this.selectGenTableData = select
    },
    // 获取数据分类数据
    getTypeDict () {
      const params = {
        dictKey: 'dataType'
      }
      queryDictByKeyApi(params).then((res) => {
        if (res.data.code === 2000) {
          const data = res.data.data
          const propArray = [{
            targetKey: 'dictId',
            hopeKey: 'value'
          }, {
            targetKey: 'dictName',
            hopeKey: 'label'
          }]
          this.dataTypeDict = data.children && data.children.length > 0 ? addProp(data.children, [], propArray) : []
        }
      })
    },
    /* 编辑衍生数据相关 */
    // 获取方法分类
    getMethodList () {
      // 定义通用方法集合
      this.commonMethodList = [{
        resId: 'COMMONMETHOD',
        resName: '计算符'
      }]
      this.methodContent = this.commonMethodContent
      queryMethodJarApi().then((res) => {
        const data = res.data.data && res.data.data.length ? res.data.data : []
        this.commonMethodList = this.commonMethodList.concat(data)
      })
    },
    // 切换方法分类下拉
    changeMethodList (value) {
      if (value === 'COMMONMETHOD') {
        this.methodContent = this.commonMethodContent
      } else {
        const params = {
          jarId: value
        }
        queryMethodApi(params).then((res) => {
          if (res.data.code === 2000) {
            this.methodContent = res.data.data && res.data.data.methods ? res.data.data.methods : []
          }
        })
      }
    },
    // 改变数据分类
    changeDerivativeDataType (value) {
      if (value.length) {
        const dataTypeId = value[value.length - 1]
        this.derInputData = this.inputTableData.filter(item => item.dataTypeId === dataTypeId)
      } else {
        this.derInputData = JSON.parse(JSON.stringify(this.inputTableData))
      }
    },
    /**
     * 得到对应视图“数据”的code代码片段
     * @param {item} [Object] 数据分类 某个数据详情
      */
    getDataCode (item) {
      const result = `DataUtil.get(this,"${item.dataCode}")`
      return result
    },
    /**
     * 得到对应视图“方法”的code代码片段
     * @param {item} [Object] 数据分类 某个数据详情
      */
    getMethodCode (item) {
      let result = [`MethodUtil.call("${item.methodCode}"`]
      if (item.parameters && item.parameters.length > 0) {
        item.parameters.forEach(ele => {
          result.push(',')
        })
      }
      result.push(')')
      return result
    },
    /**
     * 得到“方法”对应视图
     * @param {item} [Object] 数据分类 某个数据详情
      */
    getMethodName (item) {
      let result = [`调用 ( ${item.methodName}`]
      if (item.parameters && item.parameters.length > 0) {
        item.parameters.forEach(ele => {
          result.push(',')
        })
      }
      result.push(')')
      return result
    },
    // 点击数据
    handleClickDerItem (item) {
      if (this.currentTagIndex !== null) {
        this.viewList.splice(this.currentTagIndex, 0, item.dataName)
        this.sourceList.splice(this.currentTagIndex, 0, this.getDataCode(item))
        this.currentTagIndex += 1
      } else {
        this.viewList.push(item.dataName)
        this.sourceList.push(this.getDataCode(item))
      }
    },
    // 点击方法
    handleClickMethod (item) {
      // 若选中目标，则目标位置前插入合并
      if (this.currentTagIndex !== null) {
        // 若为自定义方法
        if (item.methodId) {
          const methodNameList = this.getMethodName(item)
          this.viewList.splice(this.currentTagIndex, 0, ...methodNameList)
          const methodCodeList = this.getMethodCode(item)
          this.sourceList.splice(this.currentTagIndex, 0, ...methodCodeList)
        } else {
          // 若为计算符
          this.viewList.splice(this.currentTagIndex, 0, item.methodName)
          this.sourceList.splice(this.currentTagIndex, 0, item.methodCode)
        }
        this.currentTagIndex += 1
        // 若无选中目标则 结尾push
      } else {
        // 若为自定义方法
        if (item.methodId) {
          const methodNameList = this.getMethodName(item)
          this.viewList = this.viewList.concat(methodNameList)
          const methodCodeList = this.getMethodCode(item)
          this.sourceList = this.sourceList.concat(methodCodeList)
        } else {
          // 若为计算符
          this.viewList.push(item.methodName)
          this.sourceList.push(item.methodCode)
        }
      }
    },
    // 运算值enter事件
    handleEnter () {
      if (!this.operationalValue) return false
      const reg = new RegExp(/^[a-zA-Z0-9\u4e00-\u9fa5]+$/)
      if (!reg.test(this.operationalValue)) {
        this.$Message.warning({
          content: '请输入数字、字母、汉字',
          duration: 4
        })
        return false
      }
      if (this.currentTagIndex !== null) {
        this.viewList.splice(this.currentTagIndex, 0, this.operationalValue)
        this.sourceList.splice(this.currentTagIndex, 0, this.operationalValue)
      } else {
        this.viewList.push(this.operationalValue)
        this.sourceList.push(this.operationalValue)
      }
    },
    // 关闭tag事件
    handleCloseTag (item, index) {
      this.viewList.splice(index, 1)
      this.sourceList.splice(index, 1)
    },
    // 点击tag事件
    handleClickTag (index, value) {
      this.currentTagIndex = index === this.currentTagIndex ? null : index
    },
    // 编辑衍生数据取消按钮
    cancelDerivativeEdit () {
      this.derivativeRuleShow = false
      this.viewList = []
      this.sourceList = []
    },
    // 清空按钮
    clearRule () {
      this.viewList = []
      this.sourceList = []
    },
    // 编辑衍生数据确定按钮
    certainDerivativeEdit () {
      const data = {
        dataFormat: this.viewList,
        dataFormula: this.sourceList
      }
      verification(data).then((res) => {
        if (res.data.code === 2000) {
          if (this.isNewDerivative) {
            this.derivativeForm.dataFormat = [...this.viewList]
            this.derivativeForm.dataFormula = [...this.sourceList]
            this.saveEditBaseForm(this.derivativeForm)
            this.newDataModalShow = false
          } else {
            this.editBaseForm.dataFormat = [...this.viewList]
            this.editBaseForm.dataFormula = [...this.sourceList]
            this.saveEditBaseForm(this.editBaseForm)
            this.editDataModalShow = false
          }
          this.derivativeRuleShow = false
        } else {
          this.$Message.error({
            content: res.data.msg || '请检查语法是否正确',
            duration: 4
          })
        }
      })
    }
  },
  activated () {
  },
  created () {
  },
  mounted () {
    this.getTypeDict()
    this.setTableColumns()
    // this.getTableData()
  }
}
</script>

<style>

</style>
